//
//  TXYVideoThumbFetcher.m
//  FunnyVideo
//
//  Created by 李鑫 on 15/9/1.
//  Copyright © 2015年 NewEggTech. All rights reserved.
//

#import "TXYVideoThumbFetcher.h"
#import "TXYVideoThumbCacheManger.h"

#import <AVFoundation/AVFoundation.h>
#import <CoreMedia/CoreMedia.h>

@implementation TXYVideoThumbFetcher

+ (void)fetchImageFromURL:(NSString *)urlStrs completionBlock:(TXYVideoThumbFetchBlock)block{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        UIImage *thumb = [TXYVideoThumbFetcher thumbnailImageForVideo:[NSURL URLWithString:urlStrs] atTime:2];
//        block(thumb);
//    });
}

+ (UIImage*)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    if([TXYVideoThumbCacheManger hasCache:videoURL])
    {
        return [TXYVideoThumbCacheManger getCachedThumbImage:videoURL];
    }
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 2) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    
    [TXYVideoThumbCacheManger cacheThumbImage:videoURL image:thumbnailImage];
    
    return thumbnailImage;
}
@end
